package com.yc.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author zwei
 * @create 2024-06-24 16:22
 */
public class AliOSSUtils {
    private String endpoint ="https://oss-cn-beijing.aliyuncs.com";
    private String accessKeyId="LTAI5tMaMpqNrQHS5ums69Mr";
    private  String accessKeySecret="qrCGpsNCirvOSM8wrhnj97hSMO41qw";
    private String bucketName="daiwei001";
    //实现上传图片到oss
    public String upload(MultipartFile file) throws IOException {
        InputStream inputStream=file.getInputStream();
        //避免文件覆盖
        String originalFilename=file.getOriginalFilename();
        String fileName= UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件上传
        OSS ossClient=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName,fileName,inputStream);

        //文件访问路径
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
        //关闭ossClient
        ossClient.shutdown();
        //返回上传文件的路径
        return url;
    }
}
